<?
/**
 * This file is part of XNAT light.
 *
 * XNAT light is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * XNAT light is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XNAT light.  If not, see <http://www.gnu.org/licenses/>.
 */
namespace NRG\Xnat;

use NRG\Framework\Exceptions\IllegalArgumentException as IllegalArgumentException;
use NRG\Framework\Exceptions\QueryException as QueryException;
use NRG\Framework\Common\Registry as Registry;
use NRG\Exceptions\ACLException as ACLException;
use NRG\Xnat\User as User;
use NRG\Xnat\XObject as XObject;

/**
 * XNAT security model
 *
 * @package NRG\Xnat
 */
class Security
{
    /**
     * XNAT object
     * 
     * @var NRG\Xnat\Xnat
     */
    protected $_xnat;

    /**
     * Constructor
     */
    public function __construct(Xnat $xnat)
    {
	$this->_xnat = $xnat;
    }

    /**
     * Fetch list of users/roles/projects from XNAT database
     *
     * @param NRG\Xnat\User $user
     * @param mixed $object
     * @return $array
     */
    public function getAccess(User $user, XObject $object)
    {
	if(! $project = $object->getProject())
	    throw new ACLException(ACLException::NO_PROJECT);

	/**
	 *  |C | R | U | D |
	 *  |7 | 5 | 3 | 1 |
	 */
	$query = "SELECT login AS user, tag AS project, displayname AS role FROM xdat_user " .
		"JOIN xdat_user_groupid ON " .
		"(xdat_user.xdat_user_id=xdat_user_groupid.groups_groupid_xdat_user_xdat_user_id) " .
		"JOIN xdat_usergroup ON (xdat_usergroup.id=xdat_user_groupid.groupid) " .
		"WHERE login=$1 AND tag=$2";

	$params = array($user->getUsername(), $project->getID());
	$result = $this->_xnat->query($query, $params);

	$perms = 0;

	if(count($result) == 0)
	    return $perms;
	else if(count($result) > 1)
	    throw new QueryException(QueryException::MULTI_ROW, $query, $params);

	$result = $result[0];

	switch(strtolower($result['role'])) {
	    case 'owners':
		$perms = 16;
		break;
	    case 'members':
		$perms = 12;
		break;
	    case 'collaborators':
		$perms = 5;
		break;
	}

	return $perms;
    }

    /**
     * Check ACL for user access to a particular MR Session
     *
     * @param NRG\Xnat\User $user
     * @param NRG\Xnat\Object $object
     * @return boolean
     */
    public function canRead(User $user, XObject $object)
    {
	$privs = $this->getAccess($user, $object);

	if($privs > 0)
	    return true;
	else
	    return false;
    }
}
